www.gusucode.com > C++ 各种排序算法演示(插入、希尔、冒泡、快速等)-源码程序 > C++ 各种排序算法演示(插入、希尔、冒泡、快速等)-源码程序/code/SelectSort/main.cpp

    //Download by http://www.NewXing.com
#include<iostream>
#include<ctime>
using namespace std;

//数组的第一个元素就不参与到排序中,即测试数据的第一个记录不参与排序
//为数组的第一个元素r[0]留作他用

//简单选择排序
void SelectSort(int r[],int n)
{
	int i,j,index,temp;
	int compare(0),move(0);
	for(i=1;i<n;i++)
	{
		index=i;
		for(j=i+1;j<n;j++)
		{
			compare++;
			if(r[j]<r[index])
				index=j;
			if(index!=i)
			{
				temp=r[i];
				r[i]=r[index];
				r[index]=temp;
				move+=3;
			}
		}
	}
	cout<<"比较次数:"<<compare<<endl;
	cout<<"移动次数:"<<move<<endl;
}


void main()
{
	int i;

	cout<<"简单选择排序测试:"<<endl;
	cout<<endl;

	cout<<"测试数据为正序:"<<endl;
	int select1[11]={0,2,4,6,8,10,12,14,16,18,20};
	cout<<"排序前:"<<endl;
	for(i=1;i<11;i++)//select1[0]=0不参与
		cout<<select1[i]<<' ';
	cout<<endl;
	SelectSort(select1,11);
	cout<<"排序后:"<<endl;
	for(i=1;i<11;i++)//select1[0]=0不参与
		cout<<select1[i]<<' ';
	cout<<endl;
	cout<<endl;

	cout<<"测试数据为逆序:"<<endl;
	int select2[11]={0,99,88,77,66,55,44,33,22,11,9};
	cout<<"排序前:"<<endl;
	for(i=1;i<11;i++)//select2[0]=0不参与
		cout<<select2[i]<<' ';
	cout<<endl;
	SelectSort(select2,11);
	cout<<"排序后:"<<endl;
	for(i=1;i<11;i++)//select2[0]=0不参与
		cout<<select2[i]<<' ';
	cout<<endl;
	cout<<endl;

	cout<<"测试数据为随机数据:"<<endl;
	srand((unsigned)time(NULL));
	int random[11];
	random[0]=0;//random[0]=0不参与
	for(i=1;i<11;i++)
		random[i]=rand()%20;
	cout<<"排序前:"<<endl;
	for(i=1;i<11;i++)
		cout<<random[i]<<' ';
	cout<<endl;
	SelectSort(random,11);
	cout<<"排序后:"<<endl;
	for(i=1;i<11;i++)
		cout<<random[i]<<' ';
	cout<<endl;
	cout<<endl;

	cout<<"简单选择排序测试结束。"<<endl;
	cout<<endl;
}